<?php namespace App\Controllers\Admin;

// =====================================================================
// CONTENT METHODS
// =====================================================================

class CategoriesController extends AdminController {
   
    // ---------------------------------------------------------------------        
    // postUserabm, is the function to information of users.
    // ---------------------------------------------------------------------        
    public function index() {
        $this->layout->content = \View::make('admin.contents.categories.index')->with('categories', \Categories::all());
    }
    
    // ---------------------------------------------------------------------        
    // postUserabm, is the function to information of users.
    // ---------------------------------------------------------------------        
    public function create() {
        $this->layout->content = \View::make('admin.contents.categories.abm');
    }
   
    // ---------------------------------------------------------------------        
    // postUserabm, is the function to information of users.
    // ---------------------------------------------------------------------            
    public function store() {
            
        // Require some validation
	    $rules = array(
	        'name' => 'required'
	    );
	    
        // Get the submitted data
	    $input = \Input::get();

        // Validate
	    $validation = \Validator::make($input, $rules);
	    if ($validation->fails()) {
	        return \Redirect::to('admin/contents/categories/create')->withInput()->withErrors($validation);
	    }
        
        //Create user
	    $category = \Categories::create($input);    
	    $category->active = \Input::get('active') == 'Y' ? 1 : 0;      
	    $category->save();
        
		return \Redirect::to('admin/contents/categories')->with('success','Category has been added successfully.');
	}
	
    // ---------------------------------------------------------------------        
    // getUseredit, is the function to show the user form to edit.
    // ---------------------------------------------------------------------        
    public function edit($id=null) {
            
        $category = \Categories::find($id);
        $categoryFeatured = \CategoriesFeatured::where("categoryID","=",$id)->get();
        $contentsFeaturedIDs = $categoryFeatured->lists('contentID');
        $featured = '';
        $contents = '';
        if($contentsFeaturedIDs)
        {
            $featured = \DB::table('contents')->leftjoin("categories_featured", function($join) {
                                                    $join->on('contents.contentID', '=', 'categories_featured.contentID');
                                                })
                                              ->where('categories_featured.contentID','<>','null')
                                              ->orderBy('categories_featured.order')->get();       
            $contents = \Contents::where("categoryID","=",$id)->whereNotIn('contentID', $contentsFeaturedIDs)->get();       
        }
        else $contents = \Contents::where("categoryID","=",$id)->get();       
        
        $this->layout->content = \View::make('admin.contents.categories.edit')->with(array('categoryFeatured'=>$featured,'category'=> $category, 'contents' => $contents));
    }

    // ---------------------------------------------------------------------        
    // postUseredit, is the function to edit users.
    // ---------------------------------------------------------------------            
    public function update($id) {
      
        try {
        
			$category = \Categories::find($id);
			
			$category->name = \Input::get('name');
			$category->active = \Input::get('active') ? 'Y' : 'N';
			
			if($category->save()) {
				return \Redirect::to('admin/contents/categories')->with('success','Category has been updated successfully');
			} else {
				return \Redirect::to('admin/contents/categories')->with('error','Unable to save content');
			}
		}
		catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
		    return \Redirect::to('admin/contents/categories')->with('error','Unable to find content');
		}
	}
	
    // ---------------------------------------------------------------------        
    // postContentdelete, is the function to delete content.
    // ---------------------------------------------------------------------        
	public function destroy($id=null) {
	       
		try {
	 		$categories = \Categories::find($id);
			$delete = $categories->delete();

		    if ($delete) {
		        return \Redirect::to('admin/contents/categories')->with('success', 'Category has been deleted successfully.');
		    }
		    else {
		        return \Redirect::to('admin/contents/categories')->with('error',"Category not deleted, please try again");
		    }
		}
		catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
		    return \Redirect::to('admin/contents/categories')->with('error','Unable to find content');
		}
	}
	
    // ---------------------------------------------------------------------        
    // postContentdelete, is the function to delete content.
    // ---------------------------------------------------------------------        
	public function postFeatured() {
	
        // Get the submitted data
        $input = \Input::get();
         // Require some validation
	    $rules = array(
	        'contentID' => 'required'
	    );
	    
        // Get the submitted data
	    $input = \Input::get();

        // Validate
	    $validation = \Validator::make($input, $rules);
	    if ($validation->fails()) {
	        return \Redirect::back()->withInput()->withErrors($validation);
	    }
        
        //Create user
	    $categoryFeatured = \CategoriesFeatured::create($input);
	    $categoryFeatured->save();
		return \Redirect::back()->with('success','Content has been added successfully.');
        
	}
	
    // ---------------------------------------------------------------------        
    // postContentdelete, is the function to delete content.
    // ---------------------------------------------------------------------        
	public function postRemoveFeatured() {
	
        // Get the submitted data
        $input = \Input::get();
         // Require some validation
	    $rules = array(
	        'contentID' => 'required'
	    );
	    
        // Validate
	    $validation = \Validator::make($input, $rules);
	    if ($validation->fails()) {
	        return \Redirect::back()->withInput()->withErrors($validation);
	    }
        
        try {
	 		$categories = \CategoriesFeatured::where('categoryID','=', \Input::get('categoryID'))->where('contentID','=', \Input::get('contentID'));
			$delete = $categories->delete();

		    if ($delete) {
		        return \Redirect::back()->with('success', 'Category has been deleted successfully.');
		    }
		    else {
		        return \Redirect::back()->with('error',"Category not deleted, please try again");
		    }
		}
		catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
		    return \Redirect::back()->with('error','Unable to find content');
		}
        
	}
	
	public function postOrderFeatured() {
	
        $response['success'] = false;
        $newOrderItems = \Input::get('newOrderItems');
        $categoryID = \Input::get('categoryID');
        
        $newOrder = explode('&',$newOrderItems); 
        if (is_array($newOrder)) { 
            for($i=0; $i<count($newOrder); $i++) {
                $itemID = intval(str_replace('mySortable[]=', '', $newOrder[$i])); 
                $item = \CategoriesFeatured::where('categoryID','=',$categoryID)->where('contentID', '=', $itemID)->first(); 
                $item->order = $i;
                $noErrors = $item->save();
                if (!$noErrors) break; 
            } 
            
            if ($noErrors) {
                $response['message'] = "List of items ordered successfully."; 
                $response['success'] = true;
            }
            else $response['message'] = "Failed to sort the list of items:". mysql_error(); 
        }    
        
        return \Response::json($response);
	}
}
